 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=23 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:54 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Use final liberally
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='inherit,inheritance,override,subclass,final,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Use final liberally</div>

<div class='main-body'>
 
<br>Use the <tt>final</tt> keyword liberally to communicate your intent.
<p>The <tt>final</tt> keyword has more than one meaning :
<ul>
<li>
a <tt>final</tt> class cannot be extended</li>

<li>
a <tt>final</tt> method cannot be overridden</li>

<li>
<tt>final</tt> fields, parameters, and local variables cannot change their
value once set</li>
</ul>
In the last case, "value" for primitives is understood in the usual sense,
while "value" for objects means the object's <em>identity</em>, not its <em>state</em>. Once
the identity of a <tt>final</tt> object reference is set, it can still
change its state, but not its identity.

<p>Declaring primitive fields as <tt>final</tt> automatically ensures thread-safety
for that field.
<p>Some habitually declare parameters as <tt>final</tt>, since this almost
always the desired behaviour. Others find this verbose, and of little real benefit.

<p>Consistently using <tt>final</tt> with local variables (when appropriate)
can be useful as well. It brings attention to the non-<tt>final</tt> local
variables, which usually have more logic associated with them (for example,
<tt>result</tt>
variables, accumulators, loop variables). Many find this verbose.
A reasonable approach is to use <tt>final</tt> for local variables only if there is
at least one non-<tt>final</tt> local variable in the method ; this serves
to quickly distinguish the non-<tt>final</tt> local variables from the
others.
<p>Using <tt>final</tt> :
<ul>
<li>clearly communicates your intent</li>
<li>allows the compiler and virtual machine to perform minor optimizations</li>
<li>clearly flags items which are simpler in behaviour - <tt>final</tt> says,&nbsp;
"<i>If you are looking for complexity, you won't find it here.</i>"</li>

</ul>

<b>Example</b>
<br>
<PRE>

<span class='keyword'>import</span> java.util.*;
<span class='keyword'>import</span> java.lang.reflect.Field;

<span class='comment'>/**
* This class cannot be extended.
*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> Boat {

  <span class='keyword'>public</span> Boat( <span class='keyword'>final</span> String aName, <span class='keyword'>final</span> <span class='keyword'>int</span> aLength, <span class='keyword'>final</span> Date aDateManufactured){
    fName = aName;
    fLength = aLength;
    <span class='comment'>//make a defensive copy of the date
</span>    fDateManufactured = <span class='keyword'>new</span> Date( aDateManufactured.getTime() );

    <span class='comment'>//does not compile, since argument is final:
</span>    <span class='comment'>//aDateManufactured = null;
</span>    <span class='comment'>//does not compile, since argument is final :
</span>    <span class='comment'>//aLength = 0;
</span>  }

  <span class='comment'>/**
  * Cannot be overridden, since the class itself is final.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>void</span> setDate( <span class='keyword'>final</span> Date aNewDate ){
    <span class='comment'>//even though the field is final, its state can change:
</span>    fDateManufactured.setTime( aNewDate.getTime() );

    <span class='comment'>//does not compile, since field is final:
</span>    <span class='comment'>//fDateManufactured = aNewDate;
</span>  }

  <span class='comment'>/**
  * Suitable only for debugging.
  *
  * All local variables are final except for the loop variable.
  */</span>
  <span class='keyword'>public</span> String toString() {
    <span class='keyword'>final</span> StringBuilder result = <span class='keyword'>new</span> StringBuilder();
    <span class='keyword'>final</span> String newLine = System.getProperty(<span class='literal'>"line.separator"</span>);
    result.append( <span class='keyword'>this</span>.getClass().getName() );
    result.append( <span class='literal'>" Object {"</span> );
    result.append(newLine);

    <span class='comment'>//get fields declared in this class only (no fields of superclass)
</span>    <span class='keyword'>final</span> List&lt;Field&gt; fields = Arrays.asList(<span class='keyword'>this</span>.getClass().getDeclaredFields());

    <span class='comment'>//get field names paired with their values
</span>    <span class='keyword'>for</span> ( Field field : fields ) {
      result.append(<span class='literal'>"  "</span>);
      <span class='keyword'>try</span> {
        result.append( field.getName() );
        result.append(<span class='literal'>": "</span>);
        <span class='comment'>//requires access to private field:
</span>        result.append( field.get(<span class='keyword'>this</span>) );
      }
      <span class='keyword'>catch</span> ( IllegalAccessException ex ) {
        System.out.println(ex);
      }
      result.append(newLine);
    }
    result.append(<span class='literal'>"}"</span>);
    <span class='keyword'>return</span> result.toString();
  }

  <span class='comment'>//..elided
</span>
  <span class='comment'>/// PRIVATE ////
</span>  <span class='keyword'>private</span> <span class='keyword'>final</span> String fName;
  <span class='keyword'>private</span> <span class='keyword'>final</span> <span class='keyword'>int</span> fLength;
  <span class='keyword'>private</span> <span class='keyword'>final</span> Date fDateManufactured;
} 
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicActiond838-2.html?Id=29'>Immutable objects</a> <br>
 
  
  <a href='TopicActionaf17-2.html?Id=69'>Designing for subclassing</a> <br>
 
  
  <a href='TopicAction18c3-2.html?Id=89'>Overridable methods need special care</a> <br>
 
  
  <a href='TopicAction5368-2.html?Id=90'>Remember styles of inheritance</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='23'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=23 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:54 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
